package api

import (
	"FeedXmh/app/dao"
	"fmt"
	jwt "github.com/gogf/gf-jwt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/xuri/excelize/v2"
)

var Topo = topo{}

type topo struct{}

func (a *topo) GET(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}

	//param := r.GetQueryMap()
	//show_hnum := gconv.Int(param["show_hnum"])
	//device_type := gconv.String(param["device_type"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		var list = g.List{}

		gourp_list := dao.GetPermisGroup(userid)
		area_list := dao.GetPermisArea(userid)
		farm_list := dao.GetPermisFarm(userid)
		house_list := dao.GetPermisHouse(userid)

		for _, v := range gourp_list {
			var item_group = g.Map{}
			id := gconv.String(v["id"])
			group_name := gconv.String(v["group_name"])
			group_code := gconv.String(v["group_code"])
			item_group["type"] = "group"
			item_group["id"] = id
			item_group["name"] = group_name
			item_group["group_code"] = group_code

			var match_area_list g.List
			for _, area := range area_list {
				_group_code := gconv.String(area["group_code"])
				if _group_code == group_code {
					var item_area = g.Map{}
					id := gconv.String(area["id"])
					name := gconv.String(area["name"])
					group_code := gconv.String(area["group_code"])
					item_area["type"] = "area"
					item_area["id"] = id
					item_area["name"] = name
					item_area["group_code"] = group_code

					var match_farm_list g.List
					for _, farm := range farm_list {
						_area_id := gconv.String(farm["area_id"])
						if _area_id == id {
							var item_farm = g.Map{}
							id := gconv.String(farm["id"])
							farmname := gconv.String(farm["farmname"])

							item_farm["type"] = "farm"
							item_farm["id"] = id
							item_farm["name"] = farmname

							var match_house_list g.List
							for _, house := range house_list {
								_farmid := gconv.String(house["farmid"])
								if _farmid == id {
									var item_house = g.Map{}
									id := gconv.String(house["id"])
									housename := gconv.String(house["housename"])
									item_house["type"] = "house"
									item_house["id"] = id
									item_house["name"] = housename

									match_house_list = append(match_house_list, item_house)
								}
							}
							item_farm["children"] = match_house_list

							match_farm_list = append(match_farm_list, item_farm)
						}
					}
					item_area["children"] = match_farm_list

					match_area_list = append(match_area_list, item_area)

				}
			}

			item_group["children"] = match_area_list
			list = append(list, item_group)
		}

		//获取用户具有权限的养殖场

		/*if err != nil {
			g.Log().Line().Error(err)
			res["code"] = -1
			res["msg"] = err.Error()
		} else {
			for _, v := range farm_list.List() {

				//过滤具有device_type的类型
				if device_type != "" {
					results, err := dao.GetFarmByDeviceType(gconv.Int(v["id"]), device_type)
					if err != nil {
						g.Log().Line(true).Error(err)
					} else {
						devices := results.List()
						if len(devices) == 0 {
							continue //不往下查询子节点
						}
					}
				}

				var item = g.Map{
					"id":        v["id"],
					"farmid":    v["id"],
					"companyid": v["companyid"],
					"name":      v["farmname"],
					"open":      true,
					"type":      "farm",
					"children":  nil,
				}
				//栏舍
				//house_list,err:=dao.T_house.GetTree(fmt.Sprintf("farmid=%s",gconv.String(v["id"])))
				house_list, err := dao.GetUserHouse(userid)
				if err != nil {
					g.Log().Line().Error(err)
				}
				var list1 = g.List{}
				for _, v1 := range house_list {
					//过滤具有device_type的类型
					if device_type != "" {
						results, err := dao.GetHouseByDeviceType(gconv.Int(v1["id"]), device_type)
						if err != nil {
							g.Log().Line(true).Error(err)
						} else {
							devices := results.List()
							if len(devices) == 0 {
								continue //不往下查询子节点
							}
						}
					}

					if gconv.Int(v1["farmid"]) == gconv.Int(v["id"]) {
						var item1 = g.Map{
							"id":         v1["id"],
							"houseid":    v1["id"],
							"house_type": v1["type"],
							"farmid":     v1["farmid"],
							"name":       v1["housename"],
							"open":       true,
							"type":       "house",
							"children":   nil,
						}
						//排
						var list2 = g.List{}
						if show_hnum > 0 {
							sql := ""
							if device_type != "" {
								sql = fmt.Sprintf("SELECT DISTINCT left(hnum,1) as hnum_prefix FROM v_hzgw_node WHERE houseid=%s and device_type='%s' ORDER BY hnum_prefix ASC;", gconv.String(v1["id"]), device_type)
							} else {
								sql = fmt.Sprintf("SELECT DISTINCT left(hnum,1) as hnum_prefix FROM v_hzgw_node WHERE houseid=%s ORDER BY hnum_prefix ASC;", gconv.String(v1["id"]))
							}
							dt2, err := db.GetAll(sql)
							if err != nil {
								g.Log().Line().Error(err)
							} else {
								hnumList := dt2.List()
								if len(hnumList) > 0 {
									for _, v2 := range hnumList {
										var item2 = g.Map{
											"houseid":     v1["id"],
											"hnum_prefix": v2["hnum_prefix"],
											"name":        gconv.String(v2["hnum_prefix"]) + "排",
											"open":        true,
											"type":        "hnum",
											"children":    nil,
											"isParent":    false,
										}
										list2 = append(list2, item2)
									}
								}

							}
						}
						item1["children"] = list2
						list1 = append(list1, item1)

					}

				}

				item["children"] = list1
				list = append(list, item)
			}
		}*/

		res["data"] = list
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *topo) GetNodesAsync(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}

	param := r.GetQueryMap()
	_type := gconv.String(param["type"])
	id := gconv.Int(param["id"])
	//device_type := gconv.String(param["device_type"])
	//farmid := gconv.String(param["farmid"])
	//houseid := gconv.String(param["houseid"])
	//hnum_prefix := gconv.String(param["hnum_prefix"])
	//sn := gconv.String(param["sn"])

	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	//db := g.DB(g.Cfg().GetString("custom.db_name"))
	if dao.CheckApiPermission(url, r.Method, userid) {
		if _type == "" {
			//根目录
			var list = g.List{}
			gourp_list := dao.GetPermisGroup(userid)
			area_list := dao.GetPermisArea(userid)
			farm_list := dao.GetPermisFarm(userid)
			for _, v := range gourp_list {
				var item_group = g.Map{}
				id := gconv.String(v["id"])
				group_name := gconv.String(v["group_name"])
				group_code := gconv.String(v["group_code"])
				item_group["type"] = "group"
				item_group["id"] = id
				item_group["name"] = group_name
				item_group["group_code"] = group_code

				var match_area_list g.List
				for _, area := range area_list {
					_group_code := gconv.String(area["group_code"])
					if _group_code == group_code {
						var item_area = g.Map{}
						id := gconv.String(area["id"])
						name := gconv.String(area["name"])
						group_code := gconv.String(area["group_code"])
						item_area["type"] = "area"
						item_area["id"] = id
						item_area["name"] = name
						item_area["group_code"] = group_code

						var match_farm_list g.List
						for _, farm := range farm_list {
							_area_id := gconv.String(farm["area_id"])
							if _area_id == id {
								var item_farm = g.Map{}
								id := gconv.String(farm["id"])
								farmname := gconv.String(farm["farmname"])

								item_farm["type"] = "farm"
								item_farm["id"] = id
								item_farm["name"] = farmname

								match_farm_list = append(match_farm_list, item_farm)
							}
						}
						item_area["children"] = match_farm_list

						match_area_list = append(match_area_list, item_area)

					}
				}

				item_group["children"] = match_area_list
				list = append(list, item_group)
			}
			res["data"] = list
		}
		if _type == "farm" {
			//展开house
			farmid := id
			house_list := dao.GetPermisHouse(userid)
			device_list := dao.GetPermisDevice(userid)
			var list = g.List{}
			for _, v := range house_list {
				if gconv.Int(v["farmid"]) == farmid {
					var item = g.Map{
						"id":         v["id"],
						"houseid":    v["id"],
						"house_type": v["type"],
						"farmid":     v["farmid"],
						"name":       v["housename"],
						"open":       true,
						"type":       "house",
						"children":   nil,
					}

					houseid := gconv.Int(v["id"])
					if len(device_list) > 0 {
						for _, v1 := range device_list {
							if gconv.Int(v1["houseid"]) == houseid {
								item["device_addr"] = gconv.String(v1["device_addr"])
								item["device_online"] = gconv.Int(v1["alive"])
								break
							}
						}
					}
					//查看栏舍是否有
					list = append(list, item)
				}
			}

			res["data"] = list
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
	}
	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *topo) ExportNodes(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	_type := gconv.String(params["type"])
	claims := jwt.ExtractClaims(r)
	userid := claims["userid"].(string)
	url := r.URL.Path
	if dao.CheckApiPermission(url, r.Method, userid) {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		var sql string
		if _type == "farm" {
			sql = fmt.Sprintf(`SELECT farmid,farmname,houseid,housename,addr,hnum,sn FROM v_hzgw_node WHERE farmid=%s;`, id)
		} else if _type == "house" {
			sql = fmt.Sprintf(`SELECT farmid,farmname,houseid,housename,addr,hnum,sn FROM v_hzgw_node WHERE houseid=%s;`, id)
		}
		records, err := db.GetAll(sql)
		if err != nil {
			g.Log().Line(true).Error(err)
			res["msg"] = err.Error()
			res["code"] = -1
			r.Response.WriteJson(res)
		} else {
			f := excelize.NewFile()
			defer func() {
				if err := f.Close(); err != nil {
					g.Log().Line(true).Error(err)
				}
			}()

			// 创建一个工作表
			index, err := f.NewSheet("Sheet1")
			if err != nil {
				g.Log().Line(true).Error(err)
			}

			//样式
			style_header, _ := f.NewStyle(&excelize.Style{
				Fill:      excelize.Fill{Type: "pattern", Color: []string{"#4958b9"}, Pattern: 1},
				Font:      &excelize.Font{Color: "#ffffff", Bold: true},
				Alignment: &excelize.Alignment{Vertical: "center", Horizontal: "center"},
			})

			//列宽
			f.SetColWidth("Sheet1", "A", "Z", 20)
			// 标题
			f.SetCellValue("Sheet1", "A1", "场区")
			f.SetCellValue("Sheet1", "B1", "单元")
			f.SetCellValue("Sheet1", "C1", "栏位")
			f.SetCellValue("Sheet1", "D1", "智能终端SN")
			f.SetCellValue("Sheet1", "E1", "饲喂器SN")

			f.SetCellStyle("Sheet1", "A1", "A1", style_header)
			f.SetCellStyle("Sheet1", "B1", "B1", style_header)
			f.SetCellStyle("Sheet1", "C1", "C1", style_header)
			f.SetCellStyle("Sheet1", "D1", "D1", style_header)
			f.SetCellStyle("Sheet1", "E1", "E1", style_header)
			//行
			list := records.List()
			if len(list) > 0 {
				count := 0
				for k, v := range list {
					//行数限制
					count++
					if count > 1048000 {
						break
					}

					f.SetCellValue("Sheet1", fmt.Sprintf("A%d", k+2), gconv.String(v["farmname"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("B%d", k+2), gconv.String(v["housename"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("C%d", k+2), gconv.String(v["hnum"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("D%d", k+2), gconv.String(v["addr"]))
					f.SetCellValue("Sheet1", fmt.Sprintf("E%d", k+2), gconv.String(v["sn"]))
				}
			}
			// 设置工作簿的默认工作表
			f.SetActiveSheet(index)
			f.Write(r.Response.Writer)
		}
	} else {
		res["code"] = -1
		res["msg"] = "您没有该操作权限"
		r.Response.WriteJson(res)
	}
	r.ExitAll()
}
